﻿using System;
using System.Text.RegularExpressions;
using Unread.App.Common;
using Unread.App.ViewModels;
using Windows.UI.Xaml.Data;

namespace Unread.App.Converters
{
    /// <summary>
    /// Looks for an image in a feed item, falls back to a default when nothing found
    /// </summary>
    public class ItemViewModelToImageConverter : IValueConverter
    {
        private const string DefaultFeedItemImage = "";
        private readonly static Regex ImageRegex = new Regex(@"<img[^>]*src=[""']([^'"">]*(png|jpg|jpeg|gif|bmp))[""'][^>]*>", RegexOptions.IgnoreCase);

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var feedItem = (value as ItemViewModel);
            if (feedItem == null)
                return DefaultFeedItemImage;

            var image = GetFirstImage(feedItem.Content);
            if (!string.IsNullOrWhiteSpace(image))
                return image;

            return DefaultFeedItemImage;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }

        private static string GetFirstImage(string htmlContent)
        {
            if (string.IsNullOrWhiteSpace(htmlContent))
                return null;

            var imageLinks = ImageRegex.Matches(htmlContent);
            if (imageLinks.Count == 0)
                return null;

            foreach (Match imageLink in imageLinks)
            {
                if (UrlValidator.IsValid(imageLink.Groups[1].Value))
                    return imageLink.Groups[1].Value;
            }

            return null;
        }
    }
}
